package pl.donajski.magisterka;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class SortedGenerator implements IInitialStateGenerator {

	public State getInitialState(List<Task> tasks, List<Node> nodes) {
		this.mState = new State(tasks, nodes);
		
		
		this.initialize();
		
		return this.mState;
	}

	private void initialize() {
		Collections.sort(this.mState.getTasks());
		
		for(Task t : this.mState.getTasks()) {
			
			Node best    = null;
			float bestCost = Float.MAX_VALUE;
			
			for(Node n : this.mState.getNodes()) {
				
				if(!t.canAssign(n)) {
					continue;
				}
				
				float flowU = (float) t.getOutputTransmissionRate() * t.destinationSize();
				if(t.destinationContains(n))
					flowU -= t.getOutputTransmissionRate();
				
				//float unitFlow = (float) n.getCapacityModuleOpex() / n.getCapacityModuleSize();
				float costU = (float) Math.ceil(flowU / n.getCapacityModuleSize()) * n.getCapacityModuleOpex();
				
				
				if(costU < bestCost) {
					best = n;
					bestCost = costU;
				}
			}
			
			t.setAssignment(best);
		}
		
		this.mState.setFlows();
		this.mState.calculateCost();
		
		assert(this.mState.isValid());
	}

	private State mState;
	
}
